using UnityEngine;

public class CannonPipeBehavior : CannonWheelBehavior
{
	public float minimumY = 0F;
	public float maximumY = 60F;
	
	private float rotationY = 0F;
	
	private Quaternion yQuaternion;
	
	public void Start()
	{
		Screen.lockCursor = true;
		GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>().Hide();
		rigidbody.freezeRotation = true;
	}
	
	public override void Update()
	{
		if(isLaunched)
			return;
		
		rotationX += Input.GetAxis("Mouse X") * horizontalSensibility;
		rotationY += Input.GetAxis("Mouse Y") * verticalSensibility;
		
		rotationX = ClampAngle(rotationX * horizontalSensibility, minimumX, maximumX);
		rotationY = ClampAngle(rotationY * verticalSensibility, minimumY, maximumY);
	
		xQuaternion = Quaternion.AngleAxis(rotationX, Vector3.up);
		yQuaternion = Quaternion.AngleAxis(rotationY, Vector3.right);
		
		transform.localRotation = xQuaternion * yQuaternion;
		
		if (Input.GetMouseButton(0))
		{
			isLaunched = true;
			
			GameObject player = GameObject.FindGameObjectWithTag("Player");
			player.GetComponent<PlayerController>().Launch(transform);
			
			// player.transform.RotateAroundLocal(Vector3.up, 45.0f);
			// Rigidbody playerBody = player.GetComponent<Rigidbody>();
			// playerBody.velocity = transform.forward * playerBody.velocity.magnitude;
			// playerBody.AddForce(new Vector3(playerBody.velocity.x + 50, playerBody.velocity.y, playerBody.velocity.z + 100), ForceMode.Impulse);
			
			// player.GetComponent<Rigidbody>().AddForce(new Vector3(transform.localRotation.x, transform.localRotation.y, transform.localRotation.z), ForceMode.Impulse);
			// player.GetComponent<Rigidbody>().AddForce(new Vector3(transform.localRotation.x , transform.localRotation.y * impulse, transform.localRotation.z * impulse), ForceMode.Impulse);
			// playerBody.useGravity = true;
			
			// Find all wheels in Cannon Object, and disable them.
			CannonWheelBehavior[] wheels = GameObject.FindGameObjectWithTag("Cannon").GetComponentsInChildren<CannonWheelBehavior>();
			for (int i=0;i<wheels.Length;i++) {
				wheels[i].enabled = false;
			}
			GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>().Show();
			this.enabled = false;
			
			ChangeCameraTarget(player);
		}
	}
	
	private void ChangeCameraTarget(GameObject newTarget)
	{
		Camera.mainCamera.GetComponent<ThirdPersonCamera>().target = newTarget.GetComponent<Transform>();
	}
}

